package handler

import (
	"github.com/gin-gonic/gin"
	"log"
	"loveserver/errno"
	"loveserver/model"
	"strconv"
)

type ListShield struct {
Total    uint64              `json:"total"`
DataList []model.ShieldModel `json:"dataList"`
}

// * get all shield api.
func FetchAllShield(c *gin.Context) {
	var shield model.ShieldModel
	count, shields, err := shield.GetAll()
	if err != nil {
		SendResponse(c, errno.ErrDatabase, nil)
		return
	}

	SendResponse(c, nil, ListShield{
		Total:    count,
		DataList: shields,
	})
}

// get a shield api
func FetchSingleShield(c *gin.Context) {
	var shield model.ShieldModel
	var err error

	id, _ := strconv.Atoi(c.Param("id"))
	shield.ID = uint(id)

	if shield, err = shield.Get(); err != nil {
		SendResponse(c, errno.ErrDatabase, nil)
		return
	}
	SendResponse(c, nil, shield)
}


// create a advice
func AddShield(c *gin.Context) {

	shield := model.ShieldModel{
		Keyword: 	   c.PostForm("keyword"),
		Category:     c.PostForm("category"),

	}

	//json绑定
	err :=c.BindJSON(&shield)
	if err!=nil{
		log.Fatal(err.Error())
		return
	}

	// * 创建一条记录，错误处理
	if err := shield.Create(); err != nil {
		SendResponse(c, errno.ErrDatabase, nil)
		return
	}

	// * 返回结果
	SendResponse(c, nil, "create successful.")
}

// delete a shield
func DeleteShield(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	shield :=  model.ShieldModel{}

	shield.ID = uint(id)

	if err := shield.Delete(); err != nil {
		SendResponse(c, errno.ErrDatabase, nil)
		return
	}
	SendResponse(c, nil, "delete successful.")
}


// 修改屏蔽词
func UpdateShield(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	//completed, _ := strconv.Atoi(c.PostForm("completed"))
	shield := model.ShieldModel{
		Keyword:     c.PostForm("keyword"),
		Category:  c.PostForm("category"),
	}
	//json绑定
	err :=c.BindJSON(&shield)
	if err!=nil{
		log.Fatal(err.Error())
		return
	}

	shield.ID = uint(id)
	if err := shield.Update(); err != nil {
		SendResponse(c, errno.ErrDatabase, nil)
		return
	}

	// * 返回结果
	SendResponse(c, nil, "update successful.")
}